package com.code2roc.jarmanage.servlet.depoly;

import com.code2roc.jarmanage.db.DepolyUploadVersionDB;
import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.depoly.DepolyServiceFactory;
import com.code2roc.jarmanage.model.DepolyUploadVersionDO;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class ReplaceStartServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String projectID = ConvertUtil.convert2String(paramMap.get("projectID"));
        ProjectDO entity = ProjectDB.selectOne(projectID);
        String previewUploadPath = "";
        String previewUploadFileName = "";
        String filePath = "";
        String backUpFilePath = "";
        String versionName = "";
        String versionFilePath = "";
        if (StringUtil.isEmpty(entity.getDepolyType())) {
            //jar
            previewUploadPath = entity.getJarPackagePath() + File.separator + "preupload";
            previewUploadFileName = entity.getServiceName() + "_replace.jar";

            filePath = entity.getJarPackagePath() + File.separator + entity.getServiceName() + ".jar";
            backUpFilePath = entity.getJarPackagePath() + File.separator + "backup-" + CommonUtil.getDateTagToSecond2() + ".jar";
            versionName = "upload-" + CommonUtil.getDateTagToSecond2();
            versionFilePath = entity.getJarPackagePath() + File.separator + "depolyversion" + File.separator + versionName + ".jar";
            FileUtil.initfloderPath(entity.getJarPackagePath() + File.separator + "depolyversion");
        } else {
            //war
            previewUploadPath = entity.getJarPackagePath() + File.separator + "webapps" + File.separator + "preupload";
            previewUploadFileName = entity.getServiceName() + "_replace.war";

            filePath = entity.getJarPackagePath() + File.separator + "webapps" + File.separator + entity.getServiceName() + ".war";
            backUpFilePath = entity.getJarPackagePath() + File.separator + "webapps" + File.separator + "backup-" + CommonUtil.getDateTagToSecond2() + ".war";
            versionName = "upload-" + CommonUtil.getDateTagToSecond2();
            versionFilePath = entity.getJarPackagePath() + File.separator + "webapps" + File.separator + "depolyversion" + File.separator + versionName + ".war";
            FileUtil.initfloderPath(entity.getJarPackagePath() + File.separator + "webapps" + File.separator + "depolyversion");
        }
        FileUtil.initfloderPath(previewUploadPath);
        String replaceFilePath = previewUploadPath + File.separator + previewUploadFileName;
        if (new File(filePath).exists()) {
            FileUtil.copyFile(filePath, backUpFilePath);
            FileUtil.delete(filePath);
        }

        FileUtil.copyFile(replaceFilePath, filePath);

        DepolyUploadVersionDO depolyUploadVersionDO = new DepolyUploadVersionDO();
        depolyUploadVersionDO.setVersionID(CommonUtil.getNewGuid());
        depolyUploadVersionDO.setForceKeep("0");
        depolyUploadVersionDO.setProjectID(projectID);
        depolyUploadVersionDO.setVersionName(versionName);
        depolyUploadVersionDO.setVersionPath(versionFilePath);
        depolyUploadVersionDO.setVersionRemark("");
        DepolyUploadVersionDB.insert(depolyUploadVersionDO);
        FileUtil.copyFile(filePath, versionFilePath);

        String depolyPath = "";
        if (StringUtil.isEmpty(entity.getDepolyType())) {
            depolyPath = entity.getJarPackagePath();
        }else{
            depolyPath = entity.getJarPackagePath()+ File.separator + "webapps";
        }
        File deployDir = new File(depolyPath);
        List<File> backUpFileList = Arrays.asList(deployDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("backup-");
            }
        }));
        backUpFileList.sort(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int result = 1;
                try {
                    BasicFileAttributes fileInfo1 = Files.readAttributes(Paths.get(o1.getAbsolutePath()), BasicFileAttributes.class);
                    BasicFileAttributes fileInfo2 = Files.readAttributes(Paths.get(o2.getAbsolutePath()), BasicFileAttributes.class);
                    FileTime fileTime1 = fileInfo1.creationTime();
                    FileTime fileTime2 = fileInfo2.creationTime();
                    result = fileTime2.compareTo(fileTime1);
                } catch (Exception e) {
                    LogUtil.error(e);
                }
                return result;
            }
        });
        for (int i = 0; i < backUpFileList.size(); i++) {
            if (i > ConvertUtil.convert2Int(ConfigUtil.getConfigValue("backupcount")) - 1) {
                backUpFileList.get(i).delete();
            }
        }

        List<DepolyUploadVersionDO> versionDOList = DepolyUploadVersionDB.selectRollList(projectID);
        for (int i = 0; i < versionDOList.size(); i++) {
            if (i > ConvertUtil.convert2Int(ConfigUtil.getConfigValue("uploadcount")) - 1) {
                DepolyUploadVersionDO versionDO = versionDOList.get(i);
                FileUtil.delete(versionDO.getVersionPath());
                DepolyUploadVersionDB.delete(versionDO.getVersionID());
            }
        }

        entity.setLastDepolyDate(CommonUtil.getDateFormatToSecond());
        ProjectDB.update(entity);
        new DepolyServiceFactory().CreateDeployService().start(entity);
        FileUtil.delete(replaceFilePath);
        resp.getWriter().println(result.toString());
    }
}
